package com.ffapp.helper.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisFragment;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.bean.ParamListData;
import com.ffapp.helper.util.CountDown;
import com.ffapp.helper.util.EditTextUtil;
import com.ffapp.helper.util.SoftKeyBoardListener;
import com.ffapp.helper.util.SubstringUtil;
import com.ffapp.helper.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.LogUtil;

public class FlowFragment extends BasisFragment {

    static FlowFragment fragment;

    public static FlowFragment newInstance() {
        if (fragment == null) {
            fragment = new FlowFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;

    ArrayList<ParamListData> trapezoidList;
    ArrayList<ParamListData> rectangleList;
    ArrayList<ParamListData> uShapeList;

    ArrayList<ParamListData> terminalList;

    public static int SUBMIT = 75;

    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < terminalList.size()) {
                        initSettingSaveThred(terminalList.get(subPosition));
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            PopHandle popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    if (!isFinish) {
                        showToast("设置失败，请重试");
                        dismissProgress();
                        BleUtils.stopNotify();
                    }
                    break;
            }
        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_flow);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        trapezoidList = new ArrayList<>();
        rectangleList = new ArrayList<>();
        uShapeList = new ArrayList<>();
        terminalList = new ArrayList<>();
    }


    public void setList(String sMsgObjString, int type) {
        trapezoidList.clear();
        rectangleList.clear();
        uShapeList.clear();
        terminalList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {
            //服务器数量
            String channelModel = SubstringUtil.subString(sMsgObjString, "ChannelType:");
            if (TextUtils.isEmpty(channelModel)) {
                return;
            }
            final ArrayList<String> channelModelList = new ArrayList<>();
            channelModelList.add("梯形明渠");
            channelModelList.add("矩形明渠");
            channelModelList.add("U型明渠");

            trapezoidList.add(new ParamListData("计算方式", 1, "" + channelModelList.get(Integer.valueOf(channelModel)-1), channelModelList, "AT+CHNTYPE"));
            rectangleList.add(new ParamListData("计算方式", 1, "" + channelModelList.get(Integer.valueOf(channelModel)-1), channelModelList, "AT+CHNTYPE"));
            uShapeList.add(new ParamListData("计算方式", 1, "" + channelModelList.get(Integer.valueOf(channelModel)-1), channelModelList, "AT+CHNTYPE"));

            //以下为梯形明渠
            String roughness = SubstringUtil.subString(sMsgObjString, "Roughness:");
            trapezoidList.add(new ParamListData("渠道糙率", 2, "" + roughness, "AT+CHNRN", "",2));

            String waterSlope = SubstringUtil.subString(sMsgObjString, "Waterslope:");
            trapezoidList.add(new ParamListData("水力坡度", 2, "" + waterSlope, "AT+CHNWS", "",2));

            String correctFactor = SubstringUtil.subString(sMsgObjString, "CorrectFactor:");
            trapezoidList.add(new ParamListData("修正参数", 2, "" + correctFactor, "AT+CHNCF", "",2));

            String iwlva = SubstringUtil.subString(sMsgObjString, "IdleWlval:");
            trapezoidList.add(new ParamListData("待机水位阀值", 2, "" + iwlva, "AT+IWLVAL", "",2));

            String trpBotWidth = SubstringUtil.subString(sMsgObjString, "TrpBotWidth:");     //下底宽度
            trapezoidList.add(new ParamListData("下底宽度", 2, "" + trpBotWidth, "AT+CHNTBW", "",2));

            String trpLeftSlopeAngle = SubstringUtil.subString(sMsgObjString, "TrpLeftSlopeAngle:");
            trapezoidList.add(new ParamListData("左边坡角度", 2, "" + trpLeftSlopeAngle, "AT+CHNTLSA", "",2));

            String trpRightSlopeAngle = SubstringUtil.subString(sMsgObjString, "TrpRightSlopeAngle:");
            trapezoidList.add(new ParamListData("右边坡角度", 2, "" + trpRightSlopeAngle, "AT+CHNTRSA", "",2));


            //以下为矩形明渠
            String rectBotWidth = SubstringUtil.subString(sMsgObjString, "RectBotWidth:");     //下底宽度
            rectangleList.add(new ParamListData("下底宽度", 2, "" + rectBotWidth, "AT+CHNRBW", "",2));
            //沿用梯形明渠的渠道糙率
            rectangleList.add(new ParamListData("渠道糙率", 2, "" + roughness, "AT+CHNRN", "",2));
            //沿用梯形明渠的水力坡度
            rectangleList.add(new ParamListData("水力坡度", 2, "" + waterSlope, "AT+CHNWS","",2));
            //沿用梯形明渠的流量修正参数
            rectangleList.add(new ParamListData("流量修正参数", 2, "" + correctFactor, "AT+CHNCF","",2));
            //沿用梯形明渠的待机水位阀值
            rectangleList.add(new ParamListData("待机水位阀值", 2, "" + iwlva, "AT+IWLVAL","",2));


            //以下为U形明渠
            String uSpLDepth = SubstringUtil.subString(sMsgObjString, "USpLDepth:");
            uShapeList.add(new ParamListData("衬砌深度", 2, "" + uSpLDepth, "AT+CHNUSPLD", "",2));

            String uSpUpWidth = SubstringUtil.subString(sMsgObjString, "USpUpWidth:");
            uShapeList.add(new ParamListData("上口宽度", 2, "" + uSpUpWidth, "AT+CHNUSPUW", "",2));

            String uSpBotArcRad = SubstringUtil.subString(sMsgObjString, "USpBotArcRad:");
            uShapeList.add(new ParamListData("底弧半径", 2, "" + uSpBotArcRad, "AT+CHNUSPBAR", "",2));

            //沿用U形明渠的渠道糙率
            uShapeList.add(new ParamListData("渠道糙率", 2, "" + roughness, "AT+CHNRN", "",2));
            //沿用U形明渠的水力坡度
            uShapeList.add(new ParamListData("水力坡度", 2, "" + waterSlope, "AT+CHNWS","",2));
            //沿用U形明渠的流量修正参数
            uShapeList.add(new ParamListData("流量修正参数", 2, "" + correctFactor, "AT+CHNCF","",2));
            //沿用U形明渠的待机水位阀值
            uShapeList.add(new ParamListData("待机水位阀值", 2, "" + iwlva, "AT+IWLVAL", "",2));
            switch (channelModel) {
                case "0":       //梯形明渠
                    adapter.setmListData(trapezoidList);
                    break;
                case "1":       //矩形明渠
                    adapter.setmListData(rectangleList);
                    break;
                case "2":       //U型明渠
                    adapter.setmListData(uShapeList);
                    break;
            }
        }
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }


    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        private ArrayList<ParamListData> mListData;

        public ArrayList<ParamListData> getmListData() {
            return mListData;
        }

        public void setmListData(ArrayList<ParamListData> mListData) {
            terminalList = mListData;
            this.mListData = mListData;
        }



        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new MyAdapter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListData == null ? 0 : mListData.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData flowListData = mListData.get(position);
                tvName.setText(flowListData.getName());
                switch (flowListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(flowListData.getValue()) ? flowListData.getKey() : flowListData.getValue()));
                        editText.setHint("请选择" + flowListData.getName());
                        editText.setInputType(flowListData.getinputType_REAL());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(false);//不可编辑
                        break;
                    case 2:  // edit
                        editText.setText("" + flowListData.getValue());
                        editText.setHint("请输入" + flowListData.getName());
                        editText.setInputType(flowListData.getinputType_REAL());
                        tvUnit.setVisibility(View.GONE);
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(true);//可编辑
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = mListData.get(curPosition);
                        data.setValue(s.toString());
                    }
                });
                imgSpanner.setTag(flowListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String optionValue = terminalListData.getValues().get(options1);
                        switch (optionValue) {
                            case "梯形明渠":
                                trapezoidList.get(0).setKey(optionValue);
                                adapter.setmListData(trapezoidList);
                                break;
                            case "矩形明渠":
                                rectangleList.get(0).setKey(optionValue);
                                adapter.setmListData(rectangleList);
                                break;
                            case "U型明渠":
                                uShapeList.get(0).setKey(optionValue);
                                adapter.setmListData(uShapeList);
                                break;
                        }
                        adapter.notifyDataSetChanged();
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }

    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(terminalList.get(subPosition).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });
    }

    public void initSettingSaveThred(final ParamListData terminalData) {
        String url = terminalData.getActionUrl(mContext);
        if (TextUtils.isEmpty(url)) {
            showToast(terminalData.getName() + "的值不能为空");
            dismissProgress();
            return;
        }
        mCountDownTimer.start();

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    BleLog.d("下发设置发送成功");

                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                BleLog.d("下发设置发送失败");
            }
        });
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }

}
